package me.qixiaobo.config.jackson;

import com.fasterxml.jackson.databind.ObjectMapper;
import me.qixiaobo.util.JacksonUtils;
import me.qixiaobo.util.ResultModel;
import org.apache.commons.lang3.StringUtils;

/**
 * 序列化类
 *
 * @author guoyb
 * @date 2020/1/6
 */
public class CustomerJsonSerializer {

    ObjectMapper mapper = new ObjectMapper();
    JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();

    /**
     * @param clazz   target type
     * @param include include fields
     * @param filter  filter fields
     */
    public void filter(Class<?> clazz, String include, String filter) {
        if (clazz == null) return;
        if (StringUtils.isNotBlank(include)) {
            jacksonFilter.include(clazz, include.split(","));
        }
        if (StringUtils.isNotBlank(filter)) {
            jacksonFilter.filter(clazz, filter.split(","));
        }
        mapper.addMixIn(clazz, jacksonFilter.getClass());
    }

    /**
     * 做筛选操作
     *
     * @param object
     * @return
     * @throws Exception
     */
    public ResultModel toJson(Object object) throws Exception {
        mapper.setFilterProvider(jacksonFilter);
        //此操作会筛选字段
        String s = mapper.writeValueAsString(object);
        return JacksonUtils.json2pojo(s, ResultModel.class);
    }

    public void filter(JSON json) {
        this.filter(json.type(), json.include(), json.filter());
    }

}
